package data

import (
	"context"

	"review-service/internal/biz"
	"review-service/internal/conf"
	"review-service/internal/data/mysqlquery"

	"github.com/go-kratos/kratos/v2/log"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type greeterRepo struct {
	data *Data
	log  *log.Helper
}

type Data struct {
	log *log.Helper
	db  *mysqlquery.Query
}

// NewData .
func NewData(c *conf.Data, logger log.Logger) (*Data, func(), error) {
	db, err := gorm.Open(mysql.Open(c.Database.Source), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	mysqlquery.SetDefault(db)

	cleanup := func() {
		sqlDB, err := db.DB()
		if err != nil {
			log.NewHelper(logger).Error("failed to get sql db", err.Error())
			return
		}
		// 在程序退出或不再需要连接时关闭
		defer sqlDB.Close()
		log.NewHelper(logger).Info("closing the data resources")
	}

	return &Data{log: log.NewHelper(logger), db: mysqlquery.Q}, cleanup, nil
}

// NewGreeterRepo .
func NewGreeterRepo(data *Data, logger log.Logger) biz.GreeterRepo {
	return &greeterRepo{
		data: data,
		log:  log.NewHelper(logger),
	}
}

func (r *greeterRepo) Save(ctx context.Context, g *biz.Greeter) (*biz.Greeter, error) {
	return g, nil
}

func (r *greeterRepo) Update(ctx context.Context, g *biz.Greeter) (*biz.Greeter, error) {
	return g, nil
}

func (r *greeterRepo) FindByID(context.Context, int64) (*biz.Greeter, error) {
	return nil, nil
}

func (r *greeterRepo) ListByHello(context.Context, string) ([]*biz.Greeter, error) {
	return nil, nil
}

func (r *greeterRepo) ListAll(context.Context) ([]*biz.Greeter, error) {
	return nil, nil
}
